# Copyright 2009 http://www.yuntien.com
# Licensed under the Apache License, Version 2.0

from google.appengine.ext import db

KEY_NAME_PREFIX = 'BOARD_'

class YTBoard(db.Model):
    category = db.StringProperty(multiline=False)
    ref = db.SelfReferenceProperty() 
    
    title = db.StringProperty(multiline=False)
    number = db.IntegerProperty(default=0)
    sort = db.IntegerProperty(default=0)
    date = db.DateTimeProperty(auto_now=True)
    dummy = db.BooleanProperty(default=False)
    expand = db.BooleanProperty(default=False)

    def get_parent(self):
        return self.ref
    
    def get_board_path(self):
        try:
            board_path = []
            board = self        
            while board is not None:
                board_path.append(board)
                board = board.get_parent()            
            board_path.reverse()
            return board_path
        except:
            return []
    
    def get_sub_boards(self):
        return YTBoard.all().filter('ref =', self.key()).order('sort').fetch(1000)      
  
    def get_board_key(self):
        return self.key().name()[len(KEY_NAME_PREFIX):]
    
    def __str__(self):
        return self.title    

    @classmethod
    def get_or_insert_by_name(cls, board_name, **kwds):
        try:      
            return YTBoard.get_or_insert(KEY_NAME_PREFIX+board_name, **kwds)
        except:
            return None  

    @classmethod
    def get_by_name(cls, board_name):
        return YTBoard.get_by_key_name(KEY_NAME_PREFIX+board_name)
